# encoding: utf-8
from __future__ import unicode_literals
import os
import sys
from datetime import datetime

import django
import snmpclient
from django.utils import timezone, six

APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(APP_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'traffic.settings')
django.setup()
from core.models import Host, TrafficLog, Collection


def gettraffic():
    # now = timezone.now()
    now = datetime.strptime(timezone.now().strftime('%Y-%m-%d %H:%M:00'), '%Y-%m-%d %H:%M:%S')
    hosts = Host.objects.filter(is_active=True)
    for host in hosts:
        collect = Collection()
        collect.date = now
        collect.host = host
        try:
            client = snmpclient.SnmpClient(host.hostname, host.snmp_port, [
                snmpclient.cmdgen.CommunityData('snmpuser', host.snmp_community, snmpclient.V2C)])
            ports = host.ports.filter(is_active=True)
            for port in ports:
                try:
                    traffic_in = client.get('IF-MIB::ifHCInOctets.%s' % port.oid)
                    traffic_out = client.get('IF-MIB::ifHCOutOctets.%s' % port.oid)

                    traffic_in = int(traffic_in)
                    traffic_out = int(traffic_out)
                    prev = port.traffic_logs.order_by('-date').first()
                    if prev is not None:
                        seconds = (now - prev.date).total_seconds()  # + (now - prev.date).days * 86400
                        in_bits = (traffic_in - prev.traffic_in) / seconds * 8
                        out_bits = (traffic_out - prev.traffic_out) / seconds * 8
                    else:
                        in_bits = 0
                        out_bits = 0

                    trafficlog = TrafficLog()
                    trafficlog.port = port
                    trafficlog.date = now
                    trafficlog.traffic_in = traffic_in
                    trafficlog.traffic_out = traffic_out
                    trafficlog.in_bits = in_bits
                    trafficlog.out_bits = out_bits
                    if in_bits < 0 or out_bits < 0 or (port.name.find('Trunk') < 0 and (in_bits > 10737418240 or out_bits > 10737418240)):
                        trafficlog.isvalid = False
                    trafficlog.save()
                    # print('%020s %020s %015s %015s' % (host.description, port.description, traffic_in, traffic_out))
                except Exception as e:
                    if six.PY2:
                        err_msg = e.message
                    else:
                        err_msg = e
                    print('%020s %020s Error: %s' % (host.description, port.description, err_msg))
            if host.state == '1':
                host.state = '0'
                host.changed = now
                host.save()
            collect.is_active = True
        except Exception as e:
            if six.PY2:
                err_msg = e.message
            else:
                err_msg = e
            collect.is_active = False
            collect.message = err_msg
            if host.state == '0':
                host.state = '1'
                host.changed = now
                host.save()
            print('%020s Error: %s' % (host.description, err_msg))
        collect.save()


if __name__ == '__main__':
    gettraffic()
